/** updated 2025/08/05 */
import axios from 'axios'
import { ElMessage } from 'element-plus'

const ERROR_CODE = {
  SUCCESS: 0,
  GENERIC: 4000,
  NOT_LOGIN: 3001,
  TOKEN_INVALID: 3002,
  TOKEN_EXPIRE: 3003
}

function concatUrl(...paths) {
  const cleanPaths = paths
    .map((path) => {
      if (!path) {
        return
      }
      let temp = path
      if (temp.startsWith('/')) {
        temp = temp.substring(1)
      }
      if (temp.endsWith('/')) {
        temp == temp.substring(0, temp.length)
      }
      return temp
    })
    .filter((path) => !!path)
  return '/' + cleanPaths.join('/')
}
/**
 * 服务器接口模块
 * app登录流程：
 * 请求接口
 *  返回 code==0：请求成功
 *  返回 code==3002 等用户错误，自动重新登录
 *      返回code==0 成功（authorization自动写到cookie），重新调用接口。
 *      返回code==other 提示登录错误
 * 判断是否为 lanxin 浏览器如果是使用免授权登录如果不是使用授权登录
 */
class Http {
  constructor(apiGroup, timeout) {
    timeout = timeout || 15 * 1000

    this.baseUrl = import.meta.env.VITE_API_PREFIX
    this.absoluteUrl = import.meta.env.VITE_CONTEXT_PATH
    this.apiGroup = apiGroup
    this.axios = axios.create({ baseURL: this.baseUrl, timeout })
  }

  request(options) {
    // Add showError option, default to true
    const showError = options.showError !== false
    return new Promise((resolve, reject) => {
      // 注意如果直接设置 options，重试网络时会导致url错误！
      this.axios
        .request({ ...options, url: concatUrl(this.apiGroup, options.url) })
        .then((res) => {
          if (options.raw) {
            resolve(res)
            return
          }

          const { code, data, msg } = res.data
          if (code == ERROR_CODE.SUCCESS) {
            resolve(data)
          } else {
            if (showError) {
              ElMessage.error({ showClose: true, message: msg })
            }
            reject(res.data)
          }
        })
        .catch((err) => {
          console.log('err :>> ', err)
          if (err.message == 'canceled') return
          const statusCode = err?.response?.status
          if (statusCode == 401) {
            location.href = import.meta.env.VITE_CONTEXT_PATH + '/login'
            return
          }
          const msg = err.message + ` "${options.url}"`
          if (showError) {
            ElMessage.error({ showClose: true, message: msg })
          }
          reject({ msg })
        })
    })
  }

  /**
   * 获取请求绝对url
   * @param {*} path
   * @returns
   */
  getAbsUrl(path, params) {
    if (path.startsWith('http')) {
      if (!params) {
        return path
      } else {
        const queryString = new URLSearchParams(params).toString()
        return `${path}?${queryString}`
      }
    }
    if (!params) {
      return location.origin + concatUrl(this.baseUrl, path)
    } else {
      const queryString = new URLSearchParams(params).toString()
      return `${location.origin}${concatUrl(this.baseUrl, path)}?${queryString}`
    }
  }

  /**
   * 获取页码访问绝对url
   * @param {*} path
   * @returns
   */
  getWebAbsUrl(path, params) {
    if (path.startsWith('http')) {
      if (!params) {
        return path
      } else {
        const queryString = new URLSearchParams(params).toString()
        return `${path}?${queryString}`
      }
    }

    if (!params) {
      return location.origin + concatUrl(this.absoluteUrl, path)
    } else {
      const queryString = new URLSearchParams(params).toString()
      return `${location.origin}${concatUrl(this.absoluteUrl, path)}?${queryString}`
    }
  }

  contextAwareUrl(url) {
    return concatUrl(this.baseUrl, url)
  }

  // 设置一个 Cookie，包括名称、值和过期时间
  setCookie(name, value, days) {
    var expires = ''
    if (days) {
      var date = new Date()
      date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000)
      expires = '; expires=' + date.toUTCString()
    }
    document.cookie = name + '=' + value + expires + '; path=/' + import.meta.env.VITE_APP_KEY
  }

  /**
   * 获取cookie
   * @param {*} name
   * @returns
   */
  getCookie(name) {
    const cookies = document.cookie.split(';')

    for (var i = 0; i < cookies.length; i++) {
      var cookie = cookies[i].trim().split('=')
      var cookieName = cookie[0]

      if (cookieName === name) {
        var cookieValue = decodeURIComponent(cookie[1])
        return cookieValue
      }
    }
  }
}

export default new Http()
